import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';

import '../controllers/device_detail_controller.dart';
import '../widgets/playback_main_content_widget.dart';
import '../widgets/alarm_history_widget.dart';
import '../widgets/default_main_content_widget.dart';
import '../widgets/zoomable_video_player.dart';
import '../../../routes/app_pages.dart';

class DeviceDetailView extends GetView<DeviceDetailController> {
  DeviceDetailView({super.key});

  // 跟踪横屏状态下当前按压的方向
  final RxString _fullscreenPressedDirection = ''.obs;

  // 跟踪视频缩放比例
  final RxDouble _videoScale = 1.0.obs;

  @override
  Widget build(BuildContext context) {
    return Obx(
      () =>
          controller.isFullscreen.value
              ? _buildFullscreenLayout(context)
              : _buildNormalLayout(context),
    );
  }

  // 普通布局
  Widget _buildNormalLayout(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFFFFFF),
      appBar: _buildAppBar(),
      body: SafeArea(
        child: Column(
          children: [
            // 视频画面区域
            _buildVideoArea(),

            // 主要内容区域 - 使用Expanded确保不溢出
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  color: const Color(0xFFEDF3FA),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20.r),
                    topRight: Radius.circular(20.r),
                  ),
                ),
                child: _buildMainContent(),
              ),
            ),

            // 底部Tab区域 - 固定在底部
            _buildBottomTabSection(context),

            // Tab内容区域
            _buildTabContent(),
          ],
        ),
      ),
      // 右下角悬浮下载按钮 - 只在录像回放时显示
      floatingActionButton: Obx(() {
        if (controller.currentTabIndex.value == 1) {
          return _buildDownloadFloatingButton();
        } else {
          return const SizedBox.shrink();
        }
      }),
    );
  }

  // 全屏布局
  Widget _buildFullscreenLayout(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 全屏视频
          Center(child: _buildVideoPlayer()),

          // 左上角控制按钮区域
          Positioned(
            top: 20,
            left: 30,
            child: SafeArea(
              child: Row(
                children: [
                  // 返回按钮
                  GestureDetector(
                    onTap: controller.exitFullscreen,
                    child: Container(
                      width: 40,
                      height: 40,
                      child: Image.asset(
                        'assets/images/device_detail/quanping/全屏-返回.png',
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                  SizedBox(width: 15),
                  // 缩放倍率显示
                  Obx(() {
                    if (_videoScale.value > 1.0) {
                      return Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 6,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.black.withValues(alpha: 0.7),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          '${_videoScale.value.toStringAsFixed(1)}x',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      );
                    }
                    return const SizedBox.shrink();
                  }),
                  SizedBox(width: 15),
                  // 流类型切换按钮 - 已废弃，不再显示
                  // Obx(() {
                  //   if (controller.availableStreamTypes.length <= 1) {
                  //     return const SizedBox.shrink(); // 只有一个流类型时隐藏按钮
                  //   }
                  //   return GestureDetector(
                  //     onTap: () => _showStreamTypeDropdown(),
                  //     child: Container(
                  //       width: 40,
                  //       height: 40,
                  //       decoration: BoxDecoration(
                  //         color: Colors.black.withValues(alpha: 0.7),
                  //         shape: BoxShape.circle,
                  //         border: Border.all(
                  //           color: Colors.white.withValues(alpha: 0.3),
                  //           width: 1,
                  //         ),
                  //       ),
                  //       child: Center(
                  //         child: Text(
                  //           controller.currentStreamType.value,
                  //           style: TextStyle(
                  //             color: Colors.white,
                  //             fontSize: 12.sp,
                  //             fontWeight: FontWeight.bold,
                  //           ),
                  //         ),
                  //       ),
                  //     ),
                  //   );
                  // }),
                ],
              ),
            ),
          ),

          // 左侧云台控制 - 只在实时视频时显示（录像回放和告警视频时隐藏）
          Obx(() {
            // ✅ 只在实时视频时显示云台控制
            if (controller.currentTabIndex.value != 0) {
              return const SizedBox.shrink();
            }

            final ptzType =
                controller.channelDetail.value?['ptzType']?.toString();
            final ptzTypeInt = int.tryParse(ptzType ?? '') ?? 0;
            final isPTZSupported =
                !(ptzTypeInt == 0 || ptzTypeInt == 3 || ptzTypeInt == 4);

            if (!isPTZSupported) {
              return const SizedBox.shrink();
            }
            return Positioned(
              left: 80,
              top: 0,
              bottom: 0,
              child: Center(
                child: Container(
                  width: 140,
                  height: 140,
                  decoration: BoxDecoration(
                    color: Colors.black.withValues(alpha: 0.3), // 设置透明度
                    borderRadius: BorderRadius.circular(70),
                  ),
                  child: Stack(
                    children: [
                      // 背景图片 - 根据按压方向显示对应的背景图
                      Obx(() {
                        String backgroundImage;
                        final pressedDirection =
                            _fullscreenPressedDirection.value;
                        if (pressedDirection.isNotEmpty) {
                          // 根据按压方向显示对应的背景图
                          switch (pressedDirection) {
                            case '向上':
                              backgroundImage =
                                  'assets/images/device/全屏-向上.png';
                              break;
                            case '向下':
                              backgroundImage =
                                  'assets/images/device/全屏-向下.png';
                              break;
                            case '向左':
                              backgroundImage =
                                  'assets/images/device/全屏-向左.png';
                              break;
                            case '向右':
                              backgroundImage =
                                  'assets/images/device/全屏-向右.png';
                              break;
                            default:
                              backgroundImage =
                                  'assets/images/device_detail/quanping/全屏-云台控制.png';
                          }
                        } else {
                          backgroundImage =
                              'assets/images/device_detail/quanping/全屏-云台控制.png';
                        }

                        return Image.asset(
                          backgroundImage,
                          width: 140,
                          height: 140,
                          fit: BoxFit.fill,
                        );
                      }),
                      // 上方长按区域
                      Positioned(
                        top: 10,
                        left: 50,
                        right: 50,
                        height: 30,
                        child: GestureDetector(
                          onTap: () {
                            // ✅ 检查设备是否离线
                            if (controller.isDeviceOffline) {
                              BotToast.showText(text: '设备已离线');
                              return;
                            }
                            // 短按：开始云台控制，延迟后自动停止
                            _fullscreenPressedDirection.value = '向上';
                            controller.startPTZControl('向上');

                            // 延迟1秒后自动停止
                            Future.delayed(const Duration(seconds: 1), () {
                              if (_fullscreenPressedDirection.value == '向上') {
                                _fullscreenPressedDirection.value = '';
                                controller.stopPTZControl();
                              }
                            });
                          },
                          onLongPressStart: (_) {
                            // ✅ 检查设备是否离线
                            if (controller.isDeviceOffline) {
                              BotToast.showText(text: '设备已离线');
                              return;
                            }
                            // 长按：开始云台控制
                            _fullscreenPressedDirection.value = '向上';
                            controller.startPTZControl('向上');
                          },
                          onLongPressEnd: (_) {
                            // 长按结束：停止云台控制
                            _fullscreenPressedDirection.value = '';
                            controller.stopPTZControl();
                          },
                          child: Container(color: Colors.transparent),
                        ),
                      ),
                      // 下方长按区域
                      Positioned(
                        bottom: 10,
                        left: 50,
                        right: 50,
                        height: 30,
                        child: GestureDetector(
                          onTap: () {
                            // ✅ 检查设备是否离线
                            if (controller.isDeviceOffline) {
                              BotToast.showText(text: '设备已离线');
                              return;
                            }
                            // 短按：开始云台控制，延迟后自动停止
                            _fullscreenPressedDirection.value = '向下';
                            controller.startPTZControl('向下');

                            // 延迟1秒后自动停止
                            Future.delayed(const Duration(seconds: 1), () {
                              if (_fullscreenPressedDirection.value == '向下') {
                                _fullscreenPressedDirection.value = '';
                                controller.stopPTZControl();
                              }
                            });
                          },
                          onLongPressStart: (_) {
                            // ✅ 检查设备是否离线
                            if (controller.isDeviceOffline) {
                              BotToast.showText(text: '设备已离线');
                              return;
                            }
                            // 长按：开始云台控制
                            _fullscreenPressedDirection.value = '向下';
                            controller.startPTZControl('向下');
                          },
                          onLongPressEnd: (_) {
                            // 长按结束：停止云台控制
                            _fullscreenPressedDirection.value = '';
                            controller.stopPTZControl();
                          },
                          child: Container(color: Colors.transparent),
                        ),
                      ),
                      // 左侧长按区域
                      Positioned(
                        left: 10,
                        top: 50,
                        bottom: 50,
                        width: 30,
                        child: GestureDetector(
                          onTap: () {
                            // ✅ 检查设备是否离线
                            if (controller.isDeviceOffline) {
                              BotToast.showText(text: '设备已离线');
                              return;
                            }
                            // 短按：开始云台控制，延迟后自动停止
                            _fullscreenPressedDirection.value = '向左';
                            controller.startPTZControl('向左');

                            // 延迟1秒后自动停止
                            Future.delayed(const Duration(seconds: 1), () {
                              if (_fullscreenPressedDirection.value == '向左') {
                                _fullscreenPressedDirection.value = '';
                                controller.stopPTZControl();
                              }
                            });
                          },
                          onLongPressStart: (_) {
                            // ✅ 检查设备是否离线
                            if (controller.isDeviceOffline) {
                              BotToast.showText(text: '设备已离线');
                              return;
                            }
                            // 长按：开始云台控制
                            _fullscreenPressedDirection.value = '向左';
                            controller.startPTZControl('向左');
                          },
                          onLongPressEnd: (_) {
                            // 长按结束：停止云台控制
                            _fullscreenPressedDirection.value = '';
                            controller.stopPTZControl();
                          },
                          child: Container(color: Colors.transparent),
                        ),
                      ),
                      // 右侧长按区域
                      Positioned(
                        right: 10,
                        top: 50,
                        bottom: 50,
                        width: 30,
                        child: GestureDetector(
                          onTap: () {
                            // ✅ 检查设备是否离线
                            if (controller.isDeviceOffline) {
                              BotToast.showText(text: '设备已离线');
                              return;
                            }
                            // 短按：开始云台控制，延迟后自动停止
                            _fullscreenPressedDirection.value = '向右';
                            controller.startPTZControl('向右');

                            // 延迟1秒后自动停止
                            Future.delayed(const Duration(seconds: 1), () {
                              if (_fullscreenPressedDirection.value == '向右') {
                                _fullscreenPressedDirection.value = '';
                                controller.stopPTZControl();
                              }
                            });
                          },
                          onLongPressStart: (_) {
                            // ✅ 检查设备是否离线
                            if (controller.isDeviceOffline) {
                              BotToast.showText(text: '设备已离线');
                              return;
                            }
                            // 长按：开始云台控制
                            _fullscreenPressedDirection.value = '向右';
                            controller.startPTZControl('向右');
                          },
                          onLongPressEnd: (_) {
                            // 长按结束：停止云台控制
                            _fullscreenPressedDirection.value = '';
                            controller.stopPTZControl();
                          },
                          child: Container(color: Colors.transparent),
                        ),
                      ),
                      // 中心点击区域
                      Positioned(
                        left: 40,
                        top: 40,
                        right: 40,
                        bottom: 40,
                        child: GestureDetector(
                          onTap: () {
                            BotToast.showText(text: '云台控制中心 - 长按方向键控制云台');
                          },
                          child: Container(
                            decoration: BoxDecoration(
                              color: Colors.transparent,
                              shape: BoxShape.circle,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          }),

          // 右侧功能菜单（竖排：对话、抓拍、截图、录像）
          Positioned(
            right: 100,
            top: 60,
            // bottom: 120,
            child: Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 对话 - 只在实时视频时显示（录像回放和告警视频时隐藏）
                  Obx(() {
                    // ✅ 只在实时视频时显示对话按钮
                    if (controller.currentTabIndex.value != 0) {
                      return const SizedBox.shrink();
                    }
                    return GestureDetector(
                      onTap:
                          controller.isConnectingTalk.value
                              ? null
                              : controller.startTalk,
                      child: Container(
                        width: 40,
                        height: 40,
                        margin: const EdgeInsets.only(bottom: 15),
                        child:
                            controller.isConnectingTalk.value
                                ? CircularProgressIndicator(
                                  strokeWidth: 2,
                                  valueColor: AlwaysStoppedAnimation<Color>(
                                    Colors.white,
                                  ),
                                )
                                : Image.asset(
                                  controller.isTalking.value
                                      ? 'assets/images/device_detail/hangup_after_talk.png'
                                      : 'assets/images/device_detail/quanping/全屏-对话.png',
                                  fit: BoxFit.contain,
                                ),
                      ),
                    );
                  }),

                  // 抓拍 - 只在实时视频时显示（录像回放和告警视频时隐藏）
                  Obx(() {
                    // ✅ 只在实时视频时显示抓拍按钮
                    if (controller.currentTabIndex.value != 0) {
                      return const SizedBox.shrink();
                    }
                    return GestureDetector(
                      onTap: controller.captureImage,
                      child: Container(
                        width: 40,
                        height: 40,
                        margin: const EdgeInsets.only(bottom: 15),
                        child: Image.asset(
                          'assets/images/device_detail/quanping/全屏-抓拍.png',
                          fit: BoxFit.contain,
                        ),
                      ),
                    );
                  }),
                  // 截图
                  // Obx(() {
                  //   if (controller.isPlayingAlarmVideo.value) {
                  //     return const SizedBox.shrink(); // 告警视频播放时隐藏对话按钮
                  //   }
                  //   return GestureDetector(
                  //     onTap: controller.takeScreenshot,
                  //     child: Container(
                  //       width: 40,
                  //       height: 40,
                  //       margin: const EdgeInsets.only(bottom: 15),
                  //       child: Image.asset(
                  //         'assets/images/device_detail/quanping/全屏-截图.png',
                  //         fit: BoxFit.contain,
                  //       ),
                  //     ),
                  //   );
                  // }),
                  // 录像 - 只在实时视频时显示（录像回放和告警视频时隐藏）
                  Obx(() {
                    // ✅ 只在实时视频时显示录像按钮
                    if (controller.currentTabIndex.value != 0) {
                      return const SizedBox.shrink();
                    }
                    return GestureDetector(
                      onTap: controller.startRecording,
                      child: Container(
                        width: 40,
                        height: 40,
                        child:
                            controller.isStartingRecord.value ||
                                    controller.isStoppingRecord.value
                                ? Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    valueColor: AlwaysStoppedAnimation<Color>(
                                      Colors.white,
                                    ),
                                  ),
                                )
                                : Image.asset(
                                  controller.isRecording.value
                                      ? 'assets/images/device_detail/结束录像.png'
                                      : 'assets/images/device_detail/quanping/全屏-录像.png',
                                  fit: BoxFit.contain,
                                ),
                      ),
                    );
                  }),
                ],
              ),
            ),
          ),

          // ✅ 暂停/播放按钮 - 单独放在左下角，所有模式都显示（全屏模式）
          Obx(() {
            // ✅ 只有在视频初始化完成时才显示暂停/播放按钮
            if (!controller.isVideoInitialized.value) {
              return const SizedBox.shrink();
            }

            return Positioned(
              bottom: 15,
              left: 100,
              child: GestureDetector(
                onTap: () {
                  // 如果是实时预览tab且从暂停恢复播放，需要重新拉取视频流
                  if (controller.currentTabIndex.value == 0 &&
                      !controller.isPlaying.value) {
                    print('📺 实时预览tab恢复播放（全屏左下角），重新拉取最新视频流');
                    // 重置缩放倍率
                    _videoScale.value = 1.0;
                    controller.reloadVideo();
                  } else {
                    controller.togglePlayPause();
                  }
                },
                child: Obx(
                  () => Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.black.withValues(alpha: 0.7),
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: Colors.white.withValues(alpha: 0.3),
                        width: 1,
                      ),
                    ),
                    child: Icon(
                      controller.isPlaying.value
                          ? Icons.pause
                          : Icons.play_arrow,
                      color: Colors.white,
                      size: 20,
                    ),
                  ),
                ),
              ),
            );
          }),

          // 右下角控制（倍速 + 声音控制 + 最小化）
          Positioned(
            bottom: 15,
            right: 100,
            child: Obx(
              () => Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 倍速控制 - 只在录像回放和告警视频时显示
                  if (controller.currentTabIndex.value == 1 ||
                      controller.currentTabIndex.value == 2)
                    GestureDetector(
                      onTap: () => _showPlaybackSpeedMenu(),
                      child: Container(
                        height: 40,
                        padding: const EdgeInsets.symmetric(horizontal: 12),
                        margin: const EdgeInsets.only(right: 15),
                        decoration: BoxDecoration(
                          color: Colors.black.withValues(alpha: 0.7),
                          borderRadius: BorderRadius.circular(20),
                          border: Border.all(
                            color: Colors.white.withValues(alpha: 0.3),
                            width: 1,
                          ),
                        ),
                        child: Center(
                          child: Text(
                            controller.playbackSpeed.value == 1.0
                                ? '倍速'
                                : controller.playbackSpeed.value == 0.5
                                ? '0.5x'
                                : '${controller.playbackSpeed.value.toInt()}x',
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                    ),
                  // 声音控制
                  GestureDetector(
                    onTap: controller.toggleMute,
                    child: Obx(
                      () => Container(
                        width: 40,
                        height: 40,
                        margin: const EdgeInsets.only(right: 15),
                        child: Image.asset(
                          controller.isMuted.value
                              ? 'assets/images/device_detail/quanping/全屏-静音.png'
                              : 'assets/images/device_detail/quanping/全屏-播放声音.png',
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),
                  ),
                  // 最小化（退出全屏）
                  GestureDetector(
                    onTap: controller.exitFullscreen,
                    child: Container(
                      width: 40,
                      height: 40,
                      child: Image.asset(
                        'assets/images/device_detail/quanping/全屏-最小化.png',
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // AppBar
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: const Color(0xFFFFFFFF),
      elevation: 0,
      leading: IconButton(
        onPressed: () => Get.back(),
        icon: Icon(
          Icons.arrow_back_ios,
          size: 40.w,
          color: const Color(0xFF333333),
        ),
      ),
      title: Obx(
        () => Text(
          controller.channelDetail.value?['channelName']?.toString() ?? "其他设备",
          style: TextStyle(
            fontSize: 36.sp,
            fontWeight: FontWeight.w500,
            color: const Color(0xFF333333),
          ),
        ),
      ),
      centerTitle: true,
      actions: [
        TextButton(
          onPressed: () => _showChannelInfoDialog(),
          child: Text(
            '通道信息',
            style: TextStyle(fontSize: 28.sp, color: const Color(0xFF047FF7)),
          ),
        ),
        SizedBox(width: 20.w),
      ],
    );
  }

  // 视频画面区域
  Widget _buildVideoArea() {
    return Container(
      width: double.infinity,
      height: 420.h,
      decoration: const BoxDecoration(color: Color(0xFF2C2C2C)),
      child: Stack(
        children: [
          // 视频播放器
          Obx(() {
            // ✅ 设备离线提示 - 只在实时预览tab显示
            if (controller.currentTabIndex.value == 0 &&
                controller.isDeviceOffline) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.cloud_off_outlined,
                      size: 100.w,
                      color: Colors.white54,
                    ),
                    SizedBox(height: 20.h),
                    Text(
                      '该设备已离线',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 32.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 12.h),
                    Text(
                      '请检查设备连接状态',
                      style: TextStyle(color: Colors.white70, fontSize: 24.sp),
                    ),
                  ],
                ),
              );
            }

            // ✅ 录像回放模式 - 显示"该时段暂无录像"提示
            if (controller.currentTabIndex.value == 1 &&
                controller.showNoRecordMessage.value) {
              print(
                '🚨 UI显示"该时段暂无录像"提示 - showNoRecordMessage: ${controller.showNoRecordMessage.value}',
              );
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.video_library_outlined,
                      size: 100.w,
                      color: Colors.white54,
                    ),
                    SizedBox(height: 20.h),
                    Text(
                      '该时段暂无录像',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 32.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 12.h),
                    Text(
                      '请选择其他时间段查看录像',
                      style: TextStyle(color: Colors.white70, fontSize: 24.sp),
                    ),
                  ],
                ),
              );
            }

            // ✅ 录像回放模式 - 默认提示
            if (controller.currentTabIndex.value == 1 &&
                !controller.isPlayingRecord.value &&
                !controller.isLoading.value &&
                !controller.isVideoInitialized.value &&
                !controller.showNoRecordMessage.value) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.play_circle_outline,
                      size: 100.w,
                      color: Colors.white54,
                    ),
                    SizedBox(height: 20.h),
                    Text(
                      '录像回放',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 32.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 12.h),
                    Text(
                      '请在下方选择日期和时间段查看录像',
                      style: TextStyle(color: Colors.white70, fontSize: 24.sp),
                    ),
                  ],
                ),
              );
            }

            // ✅ 告警消息模式 - 显示"暂无告警视频"提示
            if (controller.currentTabIndex.value == 2 &&
                controller.showNoAlarmVideoMessage.value) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.video_library_outlined,
                      size: 100.w,
                      color: Colors.white54,
                    ),
                    SizedBox(height: 20.h),
                    Text(
                      '该告警暂无视频',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 32.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 12.h),
                    Text(
                      '请选择其他告警记录查看视频',
                      style: TextStyle(color: Colors.white70, fontSize: 24.sp),
                    ),
                  ],
                ),
              );
            }

            // ✅ 告警消息模式 - 默认提示
            if (controller.currentTabIndex.value == 2 &&
                !controller.isPlayingAlarmVideo.value &&
                !controller.isLoading.value &&
                !controller.isVideoInitialized.value &&
                !controller.showNoAlarmVideoMessage.value) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.notifications_active_outlined,
                      size: 100.w,
                      color: Colors.white54,
                    ),
                    SizedBox(height: 20.h),
                    Text(
                      '告警消息',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 32.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 12.h),
                    Text(
                      '请在下方选择日期查看告警记录',
                      style: TextStyle(color: Colors.white70, fontSize: 24.sp),
                    ),
                  ],
                ),
              );
            }

            // ✅ 正在加载视频
            if (controller.isLoading.value) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const CircularProgressIndicator(color: Colors.white),
                    SizedBox(height: 20.h),
                    Text(
                      '正在加载视频...',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 28.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      '请稍候',
                      style: TextStyle(color: Colors.white70, fontSize: 24.sp),
                    ),
                  ],
                ),
              );
            }

            if (controller.isVideoInitialized.value &&
                controller.videoController != null) {
              return Stack(
                children: [
                  // 视频播放器 - 支持缩放和拖动
                  ZoomableVideoPlayer(
                    controller: controller.videoController!,
                    fit: BoxFit.contain,
                    onScaleChanged: (scale) {
                      _videoScale.value = scale;
                    },
                  ),
                  // 缓冲指示器
                  if (controller.isBuffering.value)
                    Container(
                      color: Colors.black.withValues(alpha: 0.3),
                      child: const Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            CircularProgressIndicator(color: Colors.white),
                            SizedBox(height: 16),
                            Text(
                              '视频缓冲中...',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  // 移除中间的播放按钮，点击功能由 ZoomableVideoPlayer 处理
                ],
              );
            }

            // 如果正在播放告警视频但视频还未初始化，显示加载状态而不是错误
            if (controller.isPlayingAlarmVideo.value) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const CircularProgressIndicator(color: Colors.white),
                    SizedBox(height: 20.h),
                    Text(
                      '正在加载视频...',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 28.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      '请稍候',
                      style: TextStyle(color: Colors.white70, fontSize: 24.sp),
                    ),
                  ],
                ),
              );
            }

            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.videocam_off, size: 120.w, color: Colors.white54),
                  SizedBox(height: 20.h),
                  Text(
                    '视频连接失败',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 32.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  SizedBox(height: 12.h),
                  Text(
                    '请检查网络连接或稍后重试',
                    style: TextStyle(color: Colors.white70, fontSize: 24.sp),
                  ),
                  SizedBox(height: 40.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ElevatedButton.icon(
                        onPressed: controller.reloadVideo,
                        icon: Icon(Icons.refresh, size: 20.sp),
                        label: Text('重新加载', style: TextStyle(fontSize: 28.sp)),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Color(0xFF047FF7),
                          foregroundColor: Colors.white,
                          padding: EdgeInsets.symmetric(
                            horizontal: 24.w,
                            vertical: 12.h,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                        ),
                      ),
                      SizedBox(width: 20.w),
                      ElevatedButton.icon(
                        onPressed: () {
                          // 显示详细错误信息的对话框
                          _showVideoErrorDialog();
                        },
                        icon: Icon(Icons.info_outline, size: 20.sp),
                        label: Text('详情', style: TextStyle(fontSize: 28.sp)),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.white24,
                          foregroundColor: Colors.white,
                          padding: EdgeInsets.symmetric(
                            horizontal: 24.w,
                            vertical: 12.h,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            );
          }),

          // ✅ 暂停/播放按钮 - 单独放在左下角，所有模式都显示
          Obx(() {
            // ✅ 只有在视频初始化完成时才显示暂停/播放按钮
            if (!controller.isVideoInitialized.value) {
              return const SizedBox.shrink();
            }

            return Positioned(
              bottom: 30.h,
              left: 30.w,
              child: GestureDetector(
                onTap: () {
                  // 如果是实时预览tab且从暂停恢复播放，需要重新拉取视频流
                  if (controller.currentTabIndex.value == 0 &&
                      !controller.isPlaying.value) {
                    print('📺 实时预览tab恢复播放（非全屏左下角），重新拉取最新视频流');
                    // 重置缩放倍率
                    _videoScale.value = 1.0;
                    controller.reloadVideo();
                  } else {
                    controller.togglePlayPause();
                  }
                },
                child: Obx(
                  () => Container(
                    width: 33,
                    height: 33,
                    decoration: BoxDecoration(
                      color: Colors.black.withValues(alpha: 0.6),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      controller.isPlaying.value
                          ? Icons.pause
                          : Icons.play_arrow,
                      color: Colors.white,
                      size: 20.w,
                    ),
                  ),
                ),
              ),
            );
          }),

          // 视频控制按钮（倍速、音频控制、全屏）- 放在右下角
          Obx(() {
            // ✅ 只有在视频初始化完成时才显示控制按钮
            if (!controller.isVideoInitialized.value) {
              return const SizedBox.shrink();
            }

            return Positioned(
              bottom: 30.h,
              right: 30.w,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 倍速控制按钮 - 只在录像回放和告警视频时显示
                  if (controller.currentTabIndex.value == 1 ||
                      controller.currentTabIndex.value == 2)
                    GestureDetector(
                      onTap: () => _showPlaybackSpeedMenu(),
                      child: Obx(
                        () => Container(
                          width: 56,
                          height: 33,
                          decoration: BoxDecoration(
                            color: Colors.black.withValues(alpha: 0.6),
                            borderRadius: BorderRadius.circular(16.5),
                          ),
                          child: Center(
                            child: Text(
                              controller.playbackSpeed.value == 1.0
                                  ? '倍速'
                                  : controller.playbackSpeed.value == 0.5
                                  ? '0.5x'
                                  : '${controller.playbackSpeed.value.toInt()}x',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 11.sp,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  if (controller.currentTabIndex.value == 1 ||
                      controller.currentTabIndex.value == 2)
                    SizedBox(width: 11),
                  // 音频控制按钮
                  GestureDetector(
                    onTap: controller.toggleMute,
                    child: Obx(
                      () => Container(
                        width: 33,
                        height: 33,
                        decoration: BoxDecoration(
                          color: Colors.black.withValues(alpha: 0.6),
                          shape: BoxShape.circle,
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(6.w),
                          child: Image.asset(
                            controller.isMuted.value
                                ? 'assets/images/device_detail/静音.png'
                                : 'assets/images/device_detail/播放声音.png',
                            fit: BoxFit.contain,
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 11),
                  // 全屏按钮
                  GestureDetector(
                    onTap: controller.toggleFullscreen,
                    child: Container(
                      width: 33,
                      height: 33,
                      decoration: BoxDecoration(
                        color: Colors.black.withValues(alpha: 0.6),
                        shape: BoxShape.circle,
                      ),
                      child: Padding(
                        padding: EdgeInsets.all(6.w),
                        child: Image.asset(
                          'assets/images/device_detail/横屏.png',
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            );
          }),

          // 左上角缩放倍率显示 - 放在最后确保显示在最上层
          Obx(() {
            if (_videoScale.value > 1.0) {
              return Positioned(
                top: 10.h,
                left: 10.w,
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 6.h,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.black.withValues(alpha: 0.7),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Text(
                    '${_videoScale.value.toStringAsFixed(1)}x',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 24.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              );
            }
            return const SizedBox.shrink();
          }),
        ],
      ),
    );
  }

  // 全屏视频播放器
  Widget _buildVideoPlayer() {
    return Obx(() {
      if (controller.isLoading.value) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const CircularProgressIndicator(color: Colors.white),
              SizedBox(height: 20.h),
              Text(
                '正在切换视频源...',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 28.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
              SizedBox(height: 8.h),
              Text(
                '请稍候',
                style: TextStyle(color: Colors.white70, fontSize: 24.sp),
              ),
            ],
          ),
        );
      }

      if (controller.isVideoInitialized.value &&
          controller.videoController != null) {
        return Stack(
          children: [
            // 视频播放器 - 支持缩放和拖动
            ZoomableVideoPlayer(
              controller: controller.videoController!,
              fit: BoxFit.contain,
              onScaleChanged: (scale) {
                _videoScale.value = scale;
              },
            ),
            // 移除中间的播放按钮，点击功能由 ZoomableVideoPlayer 处理
          ],
        );
      }

      // 如果正在播放告警视频但视频还未初始化，显示加载状态而不是错误
      if (controller.isPlayingAlarmVideo.value) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const CircularProgressIndicator(color: Colors.white),
              SizedBox(height: 20.h),
              Text(
                '正在加载视频...',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 28.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
              SizedBox(height: 8.h),
              Text(
                '请稍候',
                style: TextStyle(color: Colors.white70, fontSize: 24.sp),
              ),
            ],
          ),
        );
      }

      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.videocam_off, size: 120.w, color: Colors.white54),
            SizedBox(height: 20.h),
            Text(
              '视频加载中...',
              style: TextStyle(color: Colors.white, fontSize: 32.sp),
            ),
            SizedBox(height: 40.h),
            ElevatedButton(
              onPressed: controller.reloadVideo,
              child: Text('重新加载', style: TextStyle(fontSize: 28.sp)),
            ),
          ],
        ),
      );
    });
  }

  // 底部Tab区域 - 固定在底部
  Widget _buildBottomTabSection(BuildContext context) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: const Color(0xFFFFFFFF),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
        border: const Border(
          top: BorderSide(color: Color(0xFFE5E5E5), width: 1),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            offset: const Offset(0, -2),
            blurRadius: 10,
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(height: 10.h), // 顶部留白
          // 选中指示器
          Obx(
            () => Container(
              width: double.infinity,
              height: 6.h,
              alignment: Alignment.centerLeft,
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 300),
                width: 120.w, // 固定一个合适的指示器宽度
                height: 6.h,
                margin: EdgeInsets.only(
                  left:
                      controller.currentTabIndex.value * (Get.width / 3) +
                      (Get.width / 3 - 120.w) / 2,
                ),
                decoration: BoxDecoration(
                  color: const Color(0xFF047FF7),
                  borderRadius: BorderRadius.circular(3.r),
                ),
              ),
            ),
          ),

          // Tab内容
          SizedBox(
            height: 80.h, // 减少高度从100.h到80.h
            child: Row(
              children: [
                Expanded(child: _buildBottomTab('实时预览', 0)),
                Expanded(child: _buildBottomTab('录像回放', 1)),
                Expanded(
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      _buildBottomTab('告警消息', 2),
                      // 红色通知圆点 - 绑定真实未读数
                      Obx(() {
                        if (controller.unreadAlarmCount.value > 0) {
                          final count = controller.unreadAlarmCount.value;
                          final countText = count > 99 ? '99+' : '$count';
                          // 根据数字长度动态计算宽度
                          final textLength = countText.length;
                          final minWidth = 30.w;
                          final padding = 8.w;
                          // 单个数字时保持圆形，多个数字时使用圆角矩形
                          final width =
                              textLength == 1
                                  ? 30.w
                                  : (minWidth + (textLength - 1) * 16.w).clamp(
                                    minWidth,
                                    80.w,
                                  );

                          return Positioned(
                            right: 60.w,
                            top: 0.h,
                            child: Container(
                              width: width,
                              height: 30.h,
                              padding: EdgeInsets.symmetric(
                                horizontal: padding,
                              ),
                              decoration: BoxDecoration(
                                color: const Color(0xFFFF0202),
                                borderRadius: BorderRadius.circular(15.h),
                              ),
                              child: Center(
                                child: Text(
                                  countText,
                                  style: TextStyle(
                                    fontSize: 18.sp,
                                    fontWeight: FontWeight.w500,
                                    color: Colors.white,
                                  ),
                                  textAlign: TextAlign.center,
                                ),
                              ),
                            ),
                          );
                        } else {
                          return const SizedBox.shrink();
                        }
                      }),
                    ],
                  ),
                ),
              ],
            ),
          ),

          // 底部安全区域 - 限制最大高度
          SizedBox(
            height: MediaQuery.of(context).padding.bottom.clamp(0.0, 20.h),
          ),
        ],
      ),
    );
  }

  // 底部Tab标签
  Widget _buildBottomTab(String title, int index) {
    return GestureDetector(
      onTap: () => controller.changeTab(index),
      child: Container(
        height: 80.h, // 与SizedBox高度保持一致
        alignment: Alignment.center,
        child: Obx(
          () => Text(
            title,
            style: TextStyle(
              fontSize: 26.sp, // 稍微减小字体
              color:
                  controller.currentTabIndex.value == index
                      ? const Color(0xFF047FF7)
                      : const Color(0xFF999999),
              fontWeight:
                  controller.currentTabIndex.value == index
                      ? FontWeight.w500
                      : FontWeight.normal,
            ),
          ),
        ),
      ),
    );
  }

  /// 显示通道信息弹出框
  void _showChannelInfoDialog() {
    if (controller.channelDetail.value == null) {
      Get.snackbar('提示', '通道信息获取中，请稍后再试');
      return;
    }

    showModalBottomSheet(
      context: Get.context!,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      // shape: const RoundedRectangleBorder(
      //   borderRadius: BorderRadius.zero, // 移除圆角
      // ),
      builder:
          (context) => Container(
            decoration: BoxDecoration(
              color: Colors.white,
              // image: DecorationImage(
              //   image: AssetImage('assets/images/tanchukuang.png'),
              //   fit: BoxFit.fill,
              // ),
            ),
            child: _buildChannelInfoContent(),
          ),
    );
  }

  /// 构建通道信息内容
  Widget _buildChannelInfoContent() {
    final channelDetail = controller.channelDetail.value;

    return Container(
      padding: EdgeInsets.all(40.w),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题
          Text(
            '通道信息',
            style: TextStyle(
              fontSize: 36.sp,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF333333),
            ),
          ),
          SizedBox(height: 30.h),

          // 通道信息列表
          _buildInfoItem(
            '通道名称',
            channelDetail?['channelName']?.toString() ?? '未知',
          ),
          _buildInfoItem(
            '通道编号',
            channelDetail?['channelId']?.toString() ?? '未知',
          ),
          _buildInfoItem('云套餐', _getCloudStorageInfo(channelDetail)),
          _buildInfoItem(
            '设备类型',
            (channelDetail?['hsDeviceSubType'] == 0 ? 'NVR' : 'IPC'),
          ),
          _buildInfoItem('云台类型', _getPtzTypeName(channelDetail?['ptzType'])),
          _buildInfoItem(
            'IP地址',
            channelDetail?['remoteIp']?.toString() ?? '未知',
          ),

          SizedBox(height: 40.h),

          // 关闭按钮
          GestureDetector(
            onTap: () => Navigator.pop(Get.context!),
            child: Container(
              width: double.infinity,
              height: 88.h,
              decoration: BoxDecoration(
                color: const Color(0xFF047FF7),
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Center(
                child: Text(
                  '关闭',
                  style: TextStyle(
                    fontSize: 32.sp,
                    fontWeight: FontWeight.w500,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),

          SizedBox(height: MediaQuery.of(Get.context!).padding.bottom),
        ],
      ),
    );
  }

  /// 构建信息项
  Widget _buildInfoItem(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 12.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 200.w, // 增加label宽度，确保不换行
            child: Text(
              '$label：',
              style: TextStyle(fontSize: 28.sp, color: const Color(0xFF666666)),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 28.sp,
                color: const Color(0xFF333333),
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 获取云台类型名称
  String _getPtzTypeName(dynamic ptzType) {
    if (ptzType == null) return '未知';
    switch (ptzType) {
      case 0:
        return '未知';
      case 1:
        return '球机';
      case 2:
        return '半球';
      case 3:
        return '固定枪机';
      case 4:
        return '遥控枪机';
      default:
        return '未知';
    }
  }

  /// 获取云套餐信息
  String _getCloudStorageInfo(dynamic channelDetail) {
    if (channelDetail == null) return '无';

    final cloudStorageId = channelDetail['cloudStorageId'];
    if (cloudStorageId == null || cloudStorageId.toString().isEmpty) {
      return '无';
    }

    final cloudStorageDuration =
        channelDetail['cloudStorageDuration']?.toString() ?? '';
    final cloudStorageType = channelDetail['cloudStorageType'];

    String durationText = cloudStorageDuration;
    String typeText = '';

    // 根据cloudStorageType确定类型
    if (cloudStorageType != null) {
      switch (cloudStorageType.toString()) {
        case '1':
          typeText = '24小时';
          break;
        case '2':
          typeText = '事件';
          break;
        default:
          typeText = '未知';
      }
    }

    // 组合显示格式：X天24小时 或 X天事件
    if (durationText.isNotEmpty && typeText.isNotEmpty) {
      return '${durationText}天${typeText}';
    } else if (durationText.isNotEmpty) {
      return '${durationText}天';
    } else if (typeText.isNotEmpty) {
      return typeText;
    } else {
      return '无';
    }
  }

  /// 构建主要内容区域
  Widget _buildMainContent() {
    return Obx(() {
      switch (controller.currentTabIndex.value) {
        case 1:
          // 录像回放模式 - 显示时间刻度尺
          return PlaybackMainContentWidget(controller: controller);
        case 2:
          // 告警历史模式 - 显示告警历史内容
          return AlarmHistoryWidget(
            onTap: (videoStr) {
              print("视频播放地址: ${videoStr}");
              controller.playAlarmVideo(videoStr);
            },
          );
        default:
          // 默认模式 - 显示功能按钮和云台控制
          return DefaultMainContentWidget();
      }
    });
  }

  /// 构建Tab内容区域
  Widget _buildTabContent() {
    return Obx(() {
      switch (controller.currentTabIndex.value) {
        case 0:
          // 实时预览 - 不显示内容
          return const SizedBox.shrink();
        case 1:
          // 录像回放 - 不显示内容（已在主要内容区显示）
          return const SizedBox.shrink();
        case 2:
          // 告警历史 - 不显示内容（已在主要内容区显示）
          return const SizedBox.shrink();
        default:
          return const SizedBox.shrink();
      }
    });
  }

  /// 显示视频错误详情对话框
  void _showVideoErrorDialog() {
    showDialog(
      context: Get.context!,
      builder:
          (context) => AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16.r),
            ),
            title: Row(
              children: [
                Icon(
                  Icons.error_outline,
                  color: Color(0xFFFF6B6B),
                  size: 32.sp,
                ),
                SizedBox(width: 12.w),
                Text(
                  '视频连接问题',
                  style: TextStyle(
                    fontSize: 32.sp,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF333333),
                  ),
                ),
              ],
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '可能的原因：',
                  style: TextStyle(
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF333333),
                  ),
                ),
                SizedBox(height: 16.h),
                _buildErrorItem('• 网络连接不稳定或延迟过高'),
                _buildErrorItem('• 设备离线或网络配置有误'),
                _buildErrorItem('• 视频服务器响应超时'),
                _buildErrorItem('• 流媒体服务暂时不可用'),
                SizedBox(height: 24.h),
                Text(
                  '建议解决方案：',
                  style: TextStyle(
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF333333),
                  ),
                ),
                SizedBox(height: 16.h),
                _buildSolutionItem('1. 检查网络连接是否正常'),
                _buildSolutionItem('2. 确认设备是否在线'),
                _buildSolutionItem('3. 尝试重新加载视频'),
                _buildSolutionItem('4. 切换到其他网络环境'),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: Text(
                  '我知道了',
                  style: TextStyle(fontSize: 28.sp, color: Color(0xFF999999)),
                ),
              ),
              ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  controller.reloadVideo();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Color(0xFF047FF7),
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                  padding: EdgeInsets.symmetric(
                    horizontal: 24.w,
                    vertical: 12.h,
                  ),
                ),
                child: Text('重新加载', style: TextStyle(fontSize: 28.sp)),
              ),
            ],
          ),
    );
  }

  /// 构建错误原因项
  Widget _buildErrorItem(String text) {
    return Padding(
      padding: EdgeInsets.only(bottom: 8.h),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 24.sp,
          color: Color(0xFF666666),
          height: 1.4,
        ),
      ),
    );
  }

  /// 构建解决方案项
  Widget _buildSolutionItem(String text) {
    return Padding(
      padding: EdgeInsets.only(bottom: 8.h),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 24.sp,
          color: Color(0xFF047FF7),
          height: 1.4,
        ),
      ),
    );
  }

  /// 构建下载悬浮按钮
  Widget _buildDownloadFloatingButton() {
    return Container(
      width: 110.w,
      height: 110.w,
      margin: EdgeInsets.only(bottom: 230.h), // 留出底部Tab的空间
      decoration: BoxDecoration(
        color: const Color(0xFF047FF7),
        shape: BoxShape.circle,
        boxShadow: [
          BoxShadow(
            color: const Color(0xFF047FF7).withValues(alpha: 0.3),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(55.w),
          onTap: () {
            Get.toNamed(
              Routes.VIDEO_LIST,
              arguments: {
                'deviceId': controller.deviceId,
                'channelId': controller.channelId,
                'deviceName': controller.deviceName.value,
                'channelName':
                    controller.channelDetail.value?['name'] ?? '未知通道',
              },
            );
          },
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.download, color: Colors.white, size: 46.w),
              SizedBox(height: 4.h),
              Text(
                '下载',
                style: TextStyle(
                  fontSize: 20.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 显示播放速度选择菜单
  void _showPlaybackSpeedMenu() {
    final speeds = [0.5, 1.0, 2.0, 3.0, 4.0];
    final isFullscreen = controller.isFullscreen.value;

    // 全屏模式使用居中对话框，普通模式使用底部sheet
    if (isFullscreen) {
      _showFullscreenSpeedDialog(speeds);
    } else {
      _showNormalSpeedSheet(speeds);
    }
  }

  /// 全屏模式：居中对话框（毛玻璃效果）
  void _showFullscreenSpeedDialog(List<double> speeds) {
    showDialog(
      context: Get.context!,
      barrierColor: Colors.black.withValues(alpha: 0.5),
      builder:
          (context) => Center(
            child: Container(
              width: 300,
              decoration: BoxDecoration(
                color: Colors.black.withValues(alpha: 0.85), // 毛玻璃背景
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                  color: Colors.white.withValues(alpha: 0.2),
                  width: 1,
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.5),
                    blurRadius: 20,
                    spreadRadius: 5,
                  ),
                ],
              ),
              child: Material(
                color: Colors.transparent,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 标题
                    Padding(
                      padding: const EdgeInsets.all(20),
                      child: Text(
                        '播放速度',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                    ),

                    // 分隔线
                    Container(
                      height: 1,
                      color: Colors.white.withValues(alpha: 0.2),
                    ),

                    // 速度选项
                    ...speeds.map((speed) {
                      return Obx(() {
                        final isSelected =
                            controller.playbackSpeed.value == speed;
                        String speedText;
                        if (speed == 0.5) {
                          speedText = '0.5x';
                        } else if (speed == 1.0) {
                          speedText = '1.0x';
                        } else {
                          speedText = '${speed.toInt()}.0x';
                        }

                        return InkWell(
                          onTap: () {
                            controller.setPlaybackSpeed(speed);
                            Navigator.pop(context);
                          },
                          child: Container(
                            width: double.infinity,
                            padding: const EdgeInsets.symmetric(
                              horizontal: 20,
                              vertical: 16,
                            ),
                            decoration: BoxDecoration(
                              color:
                                  isSelected
                                      ? Colors.white.withValues(alpha: 0.2)
                                      : Colors.transparent,
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  speedText,
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Colors.white,
                                    fontWeight:
                                        isSelected
                                            ? FontWeight.bold
                                            : FontWeight.normal,
                                  ),
                                ),
                                if (isSelected)
                                  Icon(
                                    Icons.check,
                                    color: Colors.white,
                                    size: 20,
                                  ),
                              ],
                            ),
                          ),
                        );
                      });
                    }).toList(),

                    SizedBox(height: 10),
                  ],
                ),
              ),
            ),
          ),
    );
  }

  /// 普通模式：底部弹出sheet
  void _showNormalSpeedSheet(List<double> speeds) {
    showModalBottomSheet(
      context: Get.context!,
      backgroundColor: Colors.transparent,
      builder:
          (context) => Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(24.r),
                topRight: Radius.circular(24.r),
              ),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题栏
                Container(
                  padding: EdgeInsets.symmetric(vertical: 32.h),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        color: const Color(0xFFE5E7EB),
                        width: 1.w,
                      ),
                    ),
                  ),
                  child: Center(
                    child: Text(
                      '播放速度',
                      style: TextStyle(
                        fontSize: 32.sp,
                        fontWeight: FontWeight.w600,
                        color: const Color(0xFF333333),
                      ),
                    ),
                  ),
                ),

                // 速度选项列表
                ...speeds.map((speed) {
                  return Obx(() {
                    final isSelected = controller.playbackSpeed.value == speed;
                    String speedText;
                    if (speed == 0.5) {
                      speedText = '0.5倍速';
                    } else if (speed == 1.0) {
                      speedText = '正常速度';
                    } else {
                      speedText = '${speed.toInt()}倍速';
                    }

                    return InkWell(
                      onTap: () {
                        controller.setPlaybackSpeed(speed);
                        Navigator.pop(context);
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 32.w,
                          vertical: 28.h,
                        ),
                        decoration: BoxDecoration(
                          color:
                              isSelected
                                  ? const Color(
                                    0xFF047FF7,
                                  ).withValues(alpha: 0.1)
                                  : Colors.transparent,
                          border: Border(
                            bottom: BorderSide(
                              color: const Color(0xFFE5E7EB),
                              width: 1.w,
                            ),
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              speedText,
                              style: TextStyle(
                                fontSize: 30.sp,
                                color:
                                    isSelected
                                        ? const Color(0xFF047FF7)
                                        : const Color(0xFF333333),
                                fontWeight:
                                    isSelected
                                        ? FontWeight.w600
                                        : FontWeight.normal,
                              ),
                            ),
                            if (isSelected)
                              Icon(
                                Icons.check,
                                color: const Color(0xFF047FF7),
                                size: 32.sp,
                              ),
                          ],
                        ),
                      ),
                    );
                  });
                }).toList(),

                // 底部安全区域
                SizedBox(height: MediaQuery.of(context).padding.bottom + 20.h),
              ],
            ),
          ),
    );
  }
}
